package com.rural.bus.driver.service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.rural.bus.driver.config.BusConstant;
import com.rural.bus.driver.config.MyPreferenceManager;
import com.rural.bus.driver.config.PreferenceKey;

public class DistanceService extends Service {

	private double distance;
	public static boolean isStop;
	StopReceiver stopReceiver;
	private Location currLocation;
	LocationManager locationManager;
	TestLocationListener testLocationListener;

	float[] results = new float[1];

	private MyBinder myBinder = new MyBinder();

	@Override
	public void onCreate() {

		locationManager = (LocationManager) DistanceService.this.getSystemService(Context.LOCATION_SERVICE);
		testLocationListener = new TestLocationListener();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 100, testLocationListener);

		stopReceiver = new StopReceiver();
		registerReceiver(stopReceiver, new IntentFilter(BusConstant.ACTION_STOP_DISTANCE_SERVICE));
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	public void stopDistance() {
		if (locationManager != null) {
			locationManager.removeUpdates(testLocationListener);
		}
		DistanceService.this.stopSelf();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (locationManager != null) {
			locationManager.removeUpdates(testLocationListener);
		}
		unregisterReceiver(stopReceiver);
	}

	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return myBinder;
	}

	public class MyBinder extends Binder {

		public DistanceService getService() {
			return DistanceService.this;
		}
	}

	class TestLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			// 当位置发生改变时调用
			if (location != null) {
				if (currLocation == null) {
					currLocation = location;
				} else {
					Location.distanceBetween(currLocation.getLatitude(), currLocation.getLongitude(), location.getLatitude(), location.getLongitude(), results);

					float distance = results[0];
					Log.d("bus", "已经行驶距离：" + MyPreferenceManager.instance().getSharedInfoByKey(PreferenceKey.GO_DISTANCE, 0.0f) + "公里");
									
					float preDistance = MyPreferenceManager.instance().getSharedInfoByKey(PreferenceKey.GO_DISTANCE, 0.0f);
					//MyPreferenceManager.instance().putSharedInfoOfFloat(PreferenceKey.GO_DISTANCE, preDistance + distance);
					currLocation = location;
					writeLocationToFile(location, preDistance + distance);
				}
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			// 当适配器禁用时调用
		}

		@Override
		public void onProviderEnabled(String provider) {
			// 当适配器有效时调用
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// 当状态改变时调用

		}
	}

	private void writeLocationToFile(Location location, float distance) {

		String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "location";
		Log.d("bus", path);
		File file = new File(path);
		String fileName = "location.txt";
		if (!file.exists()) {
			file.mkdirs();
		}
		File file2 = new File(path, fileName);
		if (!file2.exists()) {
			try {
				file2.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(file2, true);

			StringBuffer sb = new StringBuffer();
			sb.append(System.currentTimeMillis() + "----");
			sb.append(location.getLatitude() + "," + location.getLongitude() + "----");
			sb.append("当前行程：" + distance + "\n");

			fileWriter.write(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fileWriter != null) {
					fileWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	class StopReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (BusConstant.ACTION_STOP_DISTANCE_SERVICE.equals(intent.getAction())) {
				if (locationManager != null) {
					locationManager.removeUpdates(testLocationListener);
				}
				DistanceService.this.stopSelf();
			}
		}

	}

}
